package com.cmbt.controller;

import com.alibaba.fastjson.JSON;
import com.cmbt.bean.Page;
import com.cmbt.bean.ResultEntity;
import com.cmbt.bean.User;
import com.cmbt.service.api.UserService;
import com.cmbt.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.List;

public class UserController extends BaseController {
    UserService userService = new UserServiceImpl();

    /**
     * 处理登录请求，如果账号密码正确直接跳到首页，不正确则返回错误消息
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取账户名
        String userAcct = req.getParameter("userAcct");
        // 获取密码
        String password = req.getParameter("password");
        // 获取session对象
        HttpSession session = req.getSession();
        // 业务交给service层处理
        User user = userService.login(userAcct, password);
        // 如果存在，跳转至主页
        if (user != null) {
//            req.getRequestDispatcher("/main.jsp").forward(req, resp);
//            resp.sendRedirect("/WEB-INF/main.jsp");
            // 将用户名和id存入session域用于主页使用
            session.setAttribute("userAcct",user.getUserAcct());
            session.setAttribute("userId",user.getUserId());

            ResultEntity<Object> resultEntity = ResultEntity.successWithoutData();
            String json = JSON.toJSONString(resultEntity);
            resp.getWriter().write(json);
        } else {
            // 如果不存在则返回json数据提示错误信息
            ResultEntity<String> failed = ResultEntity.failed("账号不存在或账号密码错误");
            String json = JSON.toJSONString(failed);
            resp.getWriter().write(json);
        }
    }

    /**
     * 处理用户新增请求，添加成功直接跳到首页
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void insertUser(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        // 获取账户名
        String userAcct = req.getParameter("userAcct");
        // 获取密码
        String password = req.getParameter("password");
        //获取用户用字
        String userName =req.getParameter("userName");
        //获取用户年龄
        Integer userAge = Integer.parseInt(req.getParameter("userAge"));
        //获取邮箱地址
        String userEmail =req.getParameter("userEmail");
        //获取手机号码
        String phone = req.getParameter("phone");
        //获取性别
        String sex =req.getParameter("sex");
        User user = new User();
        user.setUserAcct(userAcct);
        user.setPassword(password);
        user.setUsername(userName);
        user.setAge(userAge);
        user.setEmail(userEmail);
        user.setPhone(phone);
        user.setGender(sex);

        userService.insertUser(user);
        resp.sendRedirect("user.jsp");

    }

    public void updateUser(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("text/html;charset=UTF-8");
        // 获取账户名
        String userAcct = req.getParameter("userAcct");
        // 获取密码
        String password = req.getParameter("password");
        //获取用户用字
        String userName =req.getParameter("userName");
        //获取用户年龄
        Integer userAge = Integer.parseInt(req.getParameter("userAge"));
        //获取邮箱地址
        String userEmail =req.getParameter("userEmail");
        //获取手机号码
        String phone = req.getParameter("phone");
        //获取性别
        String sex =req.getParameter("sex");
        User user = new User();
        user.setUserAcct(userAcct);
        user.setPassword(password);
        user.setUsername(userName);
        user.setAge(userAge);
        user.setEmail(userEmail);
        user.setPhone(phone);
        user.setGender(sex);

        userService.updateUser(user);
        resp.sendRedirect("user.jsp");

    }




    /**
     * 注册处理的方法
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    public void register(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 获取账户名
        String userAcct = req.getParameter("userAcct");
        // 获取密码
        String password = req.getParameter("password");
        // 获取年龄
        String age = req.getParameter("age");
        // 获取电话
        String phone = req.getParameter("phone");
        // 获取性别
        String gender = req.getParameter("gender");
        // 获取邮箱
        String email = req.getParameter("email");
        // 获取用户姓名
        String username = req.getParameter("username");
        // 封装到实体类中
        User user = new User();
        user.setUserAcct(userAcct);
        user.setPassword(password);
        user.setAge(Integer.valueOf(age));
        user.setEmail(email);
        user.setGender(gender);
        user.setPhone(phone);
        user.setUsername(username);
        // 交给service处理具体业务
        boolean b = userService.register(user);
        // 返回的true说明添加成功，返回成功消息
        if(b){
            ResultEntity<Object> resultEntity = ResultEntity.successWithoutData();
            String json = JSON.toJSONString(resultEntity);
            resp.getWriter().write(json);
        }else {
            // 返回的false说明添加失败，返回错误消息
            ResultEntity<Object> resultEntity = ResultEntity.failed("账户已经存在！");
            String json = JSON.toJSONString(resultEntity);
            resp.getWriter().write(json);
        }
    }

    //分页展示
    public void userPageServlet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {


        //获取当前页数，首次进入时currentPage为1，点击超链接时获取currentPage页数
        int currentPage = request.getParameter("currentPage") == null ? 1 : Integer.parseInt(request.getParameter("currentPage"));


        // 2、计算从哪里开始
        //通过page实现类获得总页数，这里的16为每页数目
        int pageSize = 16;
        int totalPage = userService.getTotalPage(pageSize);


        // 3、前一页页数、后一页变量值
        int prePage = currentPage - 1 > 0 ? currentPage - 1 : currentPage;
        int nextPage = currentPage + 1 < totalPage ? currentPage + 1 : totalPage;


        //使用request.setAttribute方法便于页面中使用el语法
        request.setAttribute("totalPage", totalPage);
        request.setAttribute("prePage", prePage);
        request.setAttribute("nextPage", nextPage);
        request.setAttribute("isFirst",false);
        //获得当前页的数据
        Page page = new Page();
        page.setCurrentPage(currentPage);
        page.setPageSize(pageSize);
        //UserDaoImpl user = new UserDaoImpl();
        List<User> userList = userService.queryUserByPage(page);
        request.setAttribute("userList", userList);
        request.setAttribute("currentPage", currentPage);
        request.getRequestDispatcher("user.jsp").forward(request, response);
    }

}
